﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using MyRunDataBase;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Symbols;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Projection;
using System.Threading;
using BryhtShare;
using System.Windows.Media.Imaging;
using BryhtControls;
using BryhtCommon;
using System.IO;
using Microsoft.Phone.Shell;
using TencentWeiboSDK;

namespace MyRun.Views
{
    public partial class MapResult : PhoneApplicationPage
    {
        private GraphicsLayer graphicsLayer { get { return mapFeet.Layers["MyGraphicsLayer"] as GraphicsLayer; } }
        private static WebMercator mercator = new WebMercator();
        private int _id = 0;
        private SportModel _sport;
        public MapResult()
        {
            InitializeComponent();
            GlobalIndicator.Initialize(this);
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.ContainsKey("id"))
            {
                LoadMaps();
            }

            (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = !_sport.HasUpload;
        }

        private void LoadMaps()
        {
            _id = int.Parse(NavigationContext.QueryString["id"]);
            using (var feetDB = new MyRunDataContent())
            {
                _sport = feetDB.Sports.Single(p => p.Id == _id);
                var sportFeet = feetDB.SportFoot.Where(p => p.SportId == _id);
                Graphic lineOutRed = new Graphic()
                {
                    Symbol = this.Resources["RedLineSymbol"] as Symbol
                };
                Graphic lineInBlack = new Graphic()
                {
                    Symbol = this.Resources["BlackLineSymbol"] as Symbol
                };
                var line = new ESRI.ArcGIS.Client.Geometry.Polyline();
                var linePoints = new ESRI.ArcGIS.Client.Geometry.PointCollection();
                foreach (var item in sportFeet)
                {
                    linePoints.Add(new MapPoint(item.Longitude + _sport.ChinaOffsetLongtitude, item.Latitude + _sport.ChinaOffsetLattitude));
                }
                line.Paths.Add(linePoints);
                lineOutRed.Geometry = line;
                lineInBlack.Geometry = line;
                lineOutRed.Geometry.SpatialReference = new SpatialReference(4326);
                lineInBlack.Geometry.SpatialReference = new SpatialReference(4326);
                graphicsLayer.Graphics.Add(lineOutRed);
                graphicsLayer.Graphics.Add(lineInBlack);
                mapFeet.ZoomTo(mercator.FromGeographic(line));//地图显示线

                var beginPoint = linePoints.First();
                var endPoint = linePoints.Last();
                Graphic beginGraphic = new Graphic()
                {
                    Geometry = mercator.FromGeographic(new MapPoint(beginPoint.X, beginPoint.Y, new SpatialReference(4326))),
                    Symbol = this.Resources["BeginRemark"] as Symbol
                };
                Graphic endGraphic = new Graphic()
                {
                    Geometry = mercator.FromGeographic(new MapPoint(endPoint.X, endPoint.Y, new SpatialReference(4326))),
                    Symbol = this.Resources["EndRemark"] as Symbol
                };
                graphicsLayer.Graphics.Add(beginGraphic);
                graphicsLayer.Graphics.Add(endGraphic);
            }


        }

        private void GraphicsLayer_MouseLeftButtonDown(object sender, GraphicMouseButtonEventArgs e)
        {
        }

        //微博分享
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            ShareTool share = new ShareTool(this);
            share.LoginSuccessfulEvect += () =>
            {
                WriteableBitmap bmp = new WriteableBitmap(LayoutRoot, null);
                string content = string.Empty;
                if (_sport != null)
                {
                    var minutes = TimeSpan.Parse(_sport.Duration).TotalMinutes.ToString("0");
                    var speed = _sport.Speed.ToString("0.00");

                    content = "#我的跑步#刚刚用了" + minutes + "分钟，以" + speed + "公里/小时的速度,跑了" + _sport.Distance.ToString("0.00") + "公里~~~";
                }
                share.Share(bmp, content);
            };
            share.LoginWeibo();
        }

        //人人分享
        private void ApplicationBarIconButtonRenren_Click(object sender, EventArgs e)
        {
            ShareTool share = new ShareTool(this);
            share.LoginSuccessfulEvect += () =>
            {
                WriteableBitmap bmp = new WriteableBitmap(LayoutRoot, null);
                string content = string.Empty;
                if (_sport != null)
                {
                    var minutes = TimeSpan.Parse(_sport.Duration).TotalMinutes.ToString("0");
                    var speed = _sport.Speed.ToString("0.00");

                    content = "#我的跑步#刚刚用了" + minutes + "分钟，以" + speed + "公里/小时的速度,跑了" + _sport.Distance.ToString("0.00") + "公里~~~";
                }
                share.Share(bmp, content);
            };
            share.LoginRenren();
        }

        //QQ分享
        private void ApplicationBarIconButtonQQ_Click(object sender, EventArgs e)
        {
            WriteableBitmap bmp = new WriteableBitmap(LayoutRoot, null);
            Isolated.SaveFile("uploadpic.jpg", bmp);
            string content = string.Empty;
            if (_sport != null)
            {
                var minutes = TimeSpan.Parse(_sport.Duration).TotalMinutes.ToString("0");
                var speed = _sport.Speed.ToString("0.00");

                content = "#我的跑步#刚刚用了" + minutes + "分钟，以" + speed + "公里/小时的速度,跑了" + _sport.Distance.ToString("0.00") + "公里~~~";
            }
            try
            {
                OAuthConfigruation.Validate();
                NavigationService.Navigate(new Uri("/Views/QQUploadPhoto.xaml?state=" + Utility.UrlEncode(content), UriKind.Relative));
            }
            catch (Exception ee)
            {
                NavigationService.Navigate(new Uri("/Views/QQWeiboLogin.xaml", UriKind.Relative));
            }

        }

        //上传
        private void Upload_Click(object sender, EventArgs e)
        {
            if (Isolated.Get("LiveUserId") != null && Isolated.Get("LiveUserId").ToString() != string.Empty
                && Isolated.Get("LiveUserName") != null && Isolated.Get("LiveUserName").ToString() != string.Empty)
            {
                UploadFoots();
            }
            else//获取UserID
            {
                ShareTool share = new ShareTool(this);
                share.LoginSuccessfulEvect += () =>
                {
                    ShareSkydrive skyShare = new ShareSkydrive();
                    skyShare.GetUserInfo((successful, userId, userName) =>
                    {
                        if (successful)
                        {
                            Isolated.Set("LiveUserId", userId);
                            Isolated.Set("LiveUserName", userName);
                            UploadFoots();
                        }
                        else
                        {
                            ThrowMessage.Show(MessageType.Error, userId);
                        }

                    });
                };
                share.LoginSkydrive();
            }
        }


        private void UploadFoots()
        {
            var liveUserId = Isolated.Get("LiveUserId");
            var liveUserName = Isolated.Get("LiveUserName");
            this.Dispatcher.BeginInvoke(() =>
            {
                (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = false;
            });
            SimpleHttpRequest request = new SimpleHttpRequest("http://www.bryht.net/addsporthandler.ashx");
            request.AddPara("SportId", _sport.Id);
            request.AddPara("Calorie", _sport.Calorie);
            request.AddPara("ChinaOffsetLattitude", _sport.ChinaOffsetLattitude);
            request.AddPara("ChinaOffsetLongtitude", _sport.ChinaOffsetLongtitude);
            request.AddPara("Distance", _sport.Distance);
            request.AddPara("Duration", _sport.Duration);
            request.AddPara("Speed", _sport.Speed);
            request.AddPara("Time", _sport.Time);
            request.AddPara("LiveUserId", liveUserId);//UserId第二部分引入账户的概念
            request.AddPara("LiveUserName", liveUserName);
            request.AddPara("LiveUserWeight", Isolated.Get("Weight"));
            GlobalIndicator.Instance.IsBusy = true;
            GlobalIndicator.Instance.Text = "上传中...";
            request.Post(
              stream =>
              {
                  using (StreamWriter writer = new StreamWriter(stream))
                  {
                      using (var db = new MyRunDataContent())
                      {
                          var sportFoots = db.SportFoot.Where(p => p.SportId == _sport.Id);
                          var sportFootsCount = sportFoots.Count();
                          double i = 0.0;
                          foreach (var f in sportFoots)
                          {
                              i++;
                              writer.WriteLine(f.Speed + "," + f.TimePoint + "," + f.Longitude + "," + f.Latitude);
                              GlobalIndicator.Instance.Text = "上传中..." + (i / sportFootsCount * 100.0).ToString("0.0") + "%";
                          }
                      }
                  }
              },
              (ok, result) =>
              {
                  GlobalIndicator.Instance.IsBusy = false;
                  if (ok)
                  {
                      ThrowMessage.Show(MessageType.Prompt, "上传成功！");
                      using (var db = new MyRunDataContent())
                      {
                          var sport = db.Sports.Single(p => p.Id == _sport.Id);
                          sport.HasUpload = true;
                          db.SubmitChanges();
                      }
                  }
                  else
                  {
                      ThrowMessage.Show(MessageType.Error, "上传失败:" + result);
                      this.Dispatcher.BeginInvoke(() =>
                      {
                          (ApplicationBar.Buttons[0] as ApplicationBarIconButton).IsEnabled = true;
                      });
                  }
              });
        }

    }
}